@ECHO OFF
:: Check Windows version
IF NOT "%OS%"=="Windows_NT" GOTO Syntax
:: Check command line
ECHO.%1 | FIND "?" >NUL
IF NOT ERRORLEVEL 1 GOTO Syntax
IF [%3]==[] GOTO Syntax
:: Check if INI file exists
IF NOT EXIST "%~f1" GOTO Syntax

:: Keep variables local
SETLOCAL

:: Read variables from command line
SET INIFile="%~f1"
SET INISection=%~2
SET INIKey=%~3
SET INIValue=

:: Reset temporary variables
SET SectOK=0
SET SectFound=0
SET KeyFound=0

:: Search the INI file line by line
FOR /F "tokens=* delims=" %%A IN ('TYPE %INIFile%') DO CALL :ParseINI "%%A"

:: Display the result
ECHO.
IF NOT %SectFound%==1 (
	ECHO INI section not found
) ELSE (
	IF NOT %KeyFound%==1 (
		ECHO INI key not found
	) ELSE (
		IF DEFINED INIValue (
			ECHO.%INIFile%
			ECHO [%INISection%]
			ECHO %INIKey%=%INIValue%
		) ELSE (
			ECHO Value not defined
		)
	)
)

ENDLOCAL & SET INIValue=%INIValue%
GOTO:EOF


:ParseINI
:: Store quoted line in variable
SET Line="%~1"
:: Check if this line is the required section heading
ECHO.%Line%| FIND /I "[%INISection%]" >NUL
IF NOT ERRORLEVEL 1 (
	SET SectOK=1
	SET SectFound=1
	GOTO:EOF
)
:: Check if this line is a different section header
IF %Line:~1,1%=="[" SET SectOK=0
IF %SectOK%==0 GOTO:EOF
:: Parse any "key=value" line
FOR /F "tokens=1* delims==" %%a IN ('ECHO.%Line%') DO (
	SET Key=%%a^"
	SET Value=^"%%b
)
:: Strip quotes from key and value
SET Value=%Value:"=%
SET Key=%Key:"=%
:: Check if the key matches the required key
IF /I "%Key%"=="%INIKey%" (
	SET INIValue=%Value%
	SET KeyFound=1
)
:: In case the = sign is surrounded by spaces...
IF /I "%Key%"=="%INIKey% " (
	SET INIValue=%Value%
	SET KeyFound=1
)
:: ...strip leading space from value
IF /I "%Key%"=="%INIKey% " IF "%INIValue:~0,1%"==" " SET INIValue=%INIValue:~1%
GOTO:EOF


:Syntax
ECHO.
ECHO ReadINI.bat,  Version 1.01 for Windows NT 4 / 2000 / XP
ECHO Read a value from the specified INI file
ECHO.
ECHO Usage:  READINI  "ini_file"  "section"  "key"
ECHO.
ECHO Where:           "ini_file" is the file name of the INI file to be read
ECHO                  "section"  is the section name, without the brackets
ECHO                  "key"      is the key whose value must be read
ECHO.
ECHO Example: if MYPROG.INI looks like this:
ECHO [Section 1]
ECHO Key1=Value 1
ECHO Key2=Value 2
ECHO [Section 2]
ECHO Key1=Value 3
ECHO Key2=Value 4
ECHO.
ECHO Then the command:  READINI  "MYPROG.INI"  "section 2"  "key2"
ECHO should return:     Value 4
ECHO.
ECHO Written by Rob van der Woude
ECHO http://www.robvanderwoude.com
